package ArraySort;

import java.util.Comparator;

public class InsertSort {
    public static Comparable[] insertSort(Comparable[] anArray) {
        Comparable[] temp = new Comparable[anArray.length];
//        for(int i = 0; i < anArray.length; i++)
//        {
//            temp[i]=0;
//        }
        //  System.out.println("length is "+anArray.length);
        for (int index = 0; index < anArray.length; index++) {
            int judge = 0;
            for (int j = 0; j < temp.length; j++) {
                if (anArray[index].compareTo(temp[j]) > 0) {
                    for (int k = temp.length - 2; k >= j; k--) {
                        temp[k + 1] = temp[k];
                    }
                    judge = 1;
                }
                if (judge == 1) {
                    temp[j] = anArray[index];
                    break;
                }
            }
            if (judge == 0) {
                temp[index] = anArray[index];
            }
        }
        //循环插入，若比前一个大则后移数组元素
        return temp;
    }


    public static Comparable[] insertSort(Comparable[] anArray, Comparator<Comparable> b) {
        Comparable[] temp = new Comparable[anArray.length];
//        for(int i = 0; i < anArray.length; i++)
//        {
//            temp[i]=0;
//        }
        //  System.out.println("length is "+anArray.length);
        for (int index = 0; index < anArray.length; index++) {
            int judge = 0;
            for (int j = 0; j < temp.length; j++) {
                if (b.compare(anArray[index], temp[j]) > 0) {
                    for (int k = temp.length - 2; k >= j; k--) {
                        temp[k + 1] = temp[k];
                    }
                    judge = 1;
                }
                if (judge == 1) {
                    temp[j] = anArray[index];
                    break;
                }
            }
            if (judge == 0) {
                temp[index] = anArray[index];
            }
        }
        //循环插入，若比前一个大则后移数组元素
        return temp;
    }
}
